package bancosys.tec.utils.db.executor;

import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;

import jmine.tec.utils.UtilsMessages;

/**
 * @author Marcio Ribeiro (mmr)
 * @created Apr 26, 2007
 */
public class MysqlDbExecutor extends JdbcDbExecutor {

    private String dbName;

    /**
     * Construtor
     * 
     * @param dbName dbName
     */
    public MysqlDbExecutor(String dbName) {
        super();
        this.dbName = dbName;
    }

    /**
     * @return o char delimitador
     */
    @Override
    public char getDelimiterChar() {
        return ';';
    }

    /**
     * {@inheritDoc}
     */
    @Override
    protected void executeDrop(Connection conn) throws CouldNotExecuteException {
        try {
            Statement stmt = conn.createStatement();
            stmt.execute("DROP DATABASE IF EXISTS " + this.dbName + ";");
            stmt.execute("CREATE DATABASE " + this.dbName + " CHARACTER SET utf8 COLLATE utf8_general_ci" + ";");
            stmt.execute("ALTER DATABASE " + this.dbName + " DEFAULT CHARACTER SET utf8" + ";");
            stmt.execute("USE " + this.dbName + ";");
        } catch (SQLException e) {
            throw new CouldNotExecuteException(UtilsMessages.SQLEXCEPTION.create(), e);
        }
    }

    /**
     * converte um statement se necessário
     * 
     * @param statement o statement
     * @return o statement convertido
     */
    @Override
    public String convertStatement(String statement) {
        if (statement.startsWith("CREATE VIEW ")) {
            return statement.replaceFirst("CREATE VIEW ", "CREATE OR REPLACE VIEW ");
        }
        return statement;
    }
}